package proxy;

import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Supplier;

final class WeakCache1<K, P, V> {
	private final BiFunction<K, P, V> valueFactory;

	public WeakCache1(BiFunction<K, P, V> valueFactory) {//构造方法，，，
		this.valueFactory = Objects.requireNonNull(valueFactory);//new ProxyClassFactory()
	}

	public V get(K key, P parameter) { 
		Supplier<V> supplier = null; 
		Factory factory = null;

		while (true) {
			if (supplier != null) {
				V value = supplier.get();
				if (value != null) {
					return value; 
				}
			}
			if (factory == null) {
				factory = new Factory(key, parameter );
			}
			if (supplier == null) {
				if (supplier == null) {
					supplier = factory;
				}
			} 
		}
	}

	private final class Factory implements Supplier<V> {
		private final K key;
		private final P parameter;

		Factory(K key, P parameter) {
			this.key = key;
			this.parameter = parameter;
		}

		@Override
		public synchronized V get() {  
			V value = null;
			// valueFactory就是WeakCache的valueFactory属性，因为Factory是WeakCache的内部类，所以可以直接访问WeakCache的valueFactory属性
			value = valueFactory.apply(key, parameter);
			return value;
		}
	}

}
